package collection;

import java.util.Map;
import java.util.TreeMap;

/**
 * 测试treeMap的使用  用的排序的时候一般使用
 * hashMap线程不安全，效率高，允许key和value为null
 * hashTable线程安全，效率低,不允许key和value为null
 */
public class TestTreeMap {
    public static void main(String[] args) {
        Map<Integer,String> treeMap = new TreeMap<>();

        treeMap.put(20,"aa");
        treeMap.put(4,"bb");
        treeMap.put(60,"cc");

        System.out.println(treeMap);

        //按照key自增的方式排序
        for (Integer key:treeMap.keySet()){
            System.out.println(key+"----"+treeMap.get(key));
        }



        //测试自定义类的排序
        Map<Emp,String>  treeMap01 = new TreeMap<>();
        treeMap01.put(new Emp(100,"张哲1",5000),"厉害啊 ");
        treeMap01.put(new Emp(110,"张哲2",4000),"啊啊啊 ");
        treeMap01.put(new Emp(19,"张哲3",3000),"通天塔 ");

        for (Emp key:treeMap01.keySet()){
            System.out.println(key+"----"+treeMap01.get(key));
        }
    }
}

class Emp implements Comparable<Emp>{
    int id;
    String name;
    double salary;

    @Override
    public int compareTo(Emp o) {//0等于 负数-小于  正数-大于
       if(this.salary>o.salary){
           return 1;
       }else if(this.salary<o.salary){
           return -1;
       }else {
           return 0;
       }
    }

    @Override
    public String toString() {
        return "id:"+id+",name"+name+",salary:"+salary;
    }

    public Emp(int id, String name, double salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }
}
